package erfgame.core.entity;

import java.util.ArrayList;
import java.util.HashMap;


import erfgame.core.AbstractLongIdObject;
import erfgame.core.world.World;

public abstract class AbstractEntity 
	extends AbstractLongIdObject 
	implements Entity {
	
	private static final long serialVersionUID = 0;
	
	protected EntityType entityType;
	private transient World world;
	private transient HashMap<Object, ArrayList<EntityListener>> listeners;
	
	public AbstractEntity(long id, EntityType entityType) {
		super(id);
		this.entityType = entityType;
	}
	
	public World getWorld() {
	    return this.world;
	}
	
	public void setWorld( World world ) {
	    this.world = world;
	}
	
	public EntityType getEntityType() {
		return this.entityType;
	}

	public void addEntityListener(EntityEventType entityEventType, EntityListener listener) {
		if( this.listeners == null ) {
			this.listeners = new HashMap<Object, ArrayList<EntityListener>>();
		}
		ArrayList<EntityListener> listeners = getListeners( entityEventType );
		if( listeners == null ) {
			listeners = new ArrayList<EntityListener>(2);
			this.listeners.put( entityEventType, listeners );
		}
		listeners.add( listener );
	}

	public void removeEntityListener(EntityEventType entityEventType, EntityListener listener) {
		ArrayList<EntityListener> listeners = getListeners( entityEventType );
		if( listeners != null ) {
			listeners.remove( listener );
		}
	}

	protected ArrayList<EntityListener> getListeners( EntityEventType type ) {
		if( this.listeners != null ) {
			return this.listeners.get(type);
		} else {
			return null;
		}
	}
	
	
	@Override
	public boolean equals(AbstractLongIdObject o) {
		return super.equals(o) && ( world.equals(((AbstractEntity)o).getWorld()));
	}

	protected void fireEntityChangeEvent( EntityEvent event ) {
		ArrayList<EntityListener> listeners = getListeners( event.getType() );
		if( listeners != null ) {
			for( int i=listeners.size(); i>0; ) {
				i--;
				EntityListener listener = listeners.get( i );
				listener.entityChanged(this, event);
			}
		}
	}

	@Override
	public String toString() {
		return getEntityType().getName().getSingular() + "#" + getId();
	}
	
	
}
